package blog.service.impl;

import blog.entity.Admin;
import blog.entity.Role;
import blog.entity.UserInfo;
import blog.mapper.AdminMapper;
import blog.service.AdminService;
import blog.service.RoleService;
import blog.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author StarryX
 * @since 2020-10-01
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService, UserDetailsService {
    @Autowired
    AdminService adminService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    HttpSession session;

    // 用户登录逻辑和验证处理
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 通过用户名查询用户
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username", s));

        // 放入session
        //这里放入的对象应该是由 Admin.id 查询得来的 UserInfo 对象
        session.setAttribute("loginUserInfo",userInfoService.getOne(new QueryWrapper<UserInfo>().eq("id", admin.getInfoId())));

        //创建一个新的UserDetails对象，最后验证登陆的需要
        UserDetails userDetails=null;
        if(admin!=null){
            //System.out.println("未加密："+user.getPassword());
            //String BCryptPassword = new BCryptPasswordEncoder().encode(user.getPassword());
            // 登录后会将登录密码进行加密，然后比对数据库中的密码，数据库密码需要加密存储！
            String password = admin.getPassword();

            //创建一个集合来存放权限
            Collection<GrantedAuthority> authorities = getAuthorities(admin);
            //实例化UserDetails对象
            //以下四个boolean值的意思
//            第一个：账户是否可用（是否被删除）
//            第二个：账户没有过期
//            第三个：密码没有过期
//            第四个：账户没被锁定 （是否冻结）
            userDetails=new org.springframework.security.core.userdetails.User(s,password,
                    true,
                    true,
                    true,
                    true, authorities);
        }
        return userDetails;
    }

    // 获取角色信息
    private Collection<GrantedAuthority> getAuthorities(Admin admin){
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        Role role = roleService.getById(admin.getRoleId());
        //注意：这里每个权限前面都要加ROLE_。否在最后验证不会通过
        authList.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        return authList;
    }
}
